<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button :icon="Plus" type="primary" @click="showTrademarkDialog">添加</el-button>
      </div>
    </template>
    <el-table v-loading="loading" :data="trademarkList" border style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="80" />
      <el-table-column align="center" prop="tmName" label="品牌名称" width="180" />
      <el-table-column align="center" label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="height:100px">
          <!-- {{ row.logoUrl }} -->
        </template>
      </el-table-column>
      <el-table-column align="center" prop="address" label="操作" width="180">
        <template v-slot="{ row }">
          <el-button title="编辑" size="small" type="warning" :icon="Edit" @click="editTrademarkInfo(row)" />
          <el-button title="删除" size="small" type="danger" :icon="Delete" @click="removeTrademarkInfo(row)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 6, 9, 12]"
      :small="small" :disabled="disabled" :background="background" layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top:20px" />
  </el-card>

  <!-- 添加-对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="`${trademark.id ? '修改' : '添加'}品牌`">
    <el-form :rules="rules" ref="trademarkForm" :model="trademark">
      <el-form-item label="品牌名称" prop="tmName" label-width="100px">
        <el-input v-model="trademark.tmName" autocomplete="off" />
        <!-- <el-input autocomplete="off" /> -->
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100px">
        <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="trademark.logoUrl" :src="trademark.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png/jpeg 文件，且不超过2M大小
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(trademarkForm)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script lang="ts">
export default {
  name: 'Trademark'
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete, UploadFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'

// 引入接口
import type { TrademarkListModel, TrademarkModel } from "@/api/product/model/trademarkModel";

// 导入请求方法
import { reqGetAllTrademarkListData, reqSaveTrademarkInfo, reqDeleteTrademarkInfo, reqUpdateTrademarkInfo } from '@/api/product/trademark'


// 分页器数据
// 分页器中带的
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const currentPage = ref(1)    // 当前页码 默认是1
const pageSize = ref(3)  // 每页显示的条数  默认是3
const loading = ref(true) // 加载loading效果

// 添加-对话框
const BASE_URL = import.meta.env.VITE_API_URL; // 添加一个全局变量
const dialogFormVisible = ref(false) // 对话框是否显示
// const imageUrl = ref(''); // 上传的图片

let initTrademark = () => ({ tmName: '', logoUrl: '' });
let trademark = reactive<TrademarkModel>(initTrademark())


let trademarkList = ref<TrademarkListModel>([]);
let total = ref(0) // 品牌总数量
// console.log('aa', trademarkList);

const trademarkForm = ref<FormInstance>(); // 定义一个ref值和el-form绑定

// 书写校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请添加品牌名称', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在2-6之间', trigger: 'blur' }
  ],
  logoUrl: [
    { required: true, message: '请选择要上传的图片', trigger: 'change' }
  ]
})

// 发送请求重新渲染页面
const getTrademarkListData = async () => {
  const res = await reqGetAllTrademarkListData(currentPage.value, pageSize.value);
  // console.log(res); // 404报错,超时，网络太慢
  // 将请求到的数据渲染到页面
  trademarkList.value = res.records; // 此处需要类型约束，不然会报错，但是报错不会影响程序的正常运行
  total.value = res.total; // 与上相同，会报错，但不影响，稍后处理
  // 隐藏loading效果
  loading.value = false;
}
// 函数挂载时发送请求
onMounted(() => {
  getTrademarkListData();
})

// 每页条数改变时调用此方法
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)  // 测试打印
  pageSize.value = val; // 每页条数的数据改变
  currentPage.value = 1; // 每页条数改变时需要将当前页页码改为 1
  // 然后重新发请求
  getTrademarkListData();
}
// 当前页改变时调用此方法
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`)
  currentPage.value = val; // 改变当前页
  // 重新发送请求渲染页面
  getTrademarkListData();
}


// 添加对话框方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // console.log(response, uploadFile);
  // trademark.logoUrl = URL.createObjectURL(uploadFile.raw!);
  // console.log('---', URL.createObjectURL(uploadFile.raw!));
  trademark.logoUrl = response.data;

  // 图片上传成功后，也要清除表单验证
  trademarkForm.value?.clearValidate(['logoUrl']);
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  const imgTypes = ['image/jpeg', 'image/jpg', 'image/png']; // 上传的图片类型
  // if (rawFile.type !== 'image/jpeg') {
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('上传图片的格式只能是jpg/png/jpeg，请重新选择')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {  // 限定图片大小不大于为 2 MB
    ElMessage.error('图片大小不能超过2MB！请重新选择！')
    return false
  }
  return true
}

// 弹出框 确认添加按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  // console.log('测试');
  // console.log(formEl);
  if (!formEl) return; // 不符合验证则直接退出
  await formEl.validate(async (valid, fields) => {
    // console.log('valid:', valid);
    // console.log('-------');
    // console.log('fields:', fields);
    if (valid) {
      if (trademark.id) {
        // 更新操作
        await reqUpdateTrademarkInfo(trademark);
      } else {
        // 添加操作
        // 发送请求，添加品牌
        await reqSaveTrademarkInfo(trademark);
        currentPage.value = 1;  // 跳转到第一页
      }

      // 提示添加成功
      ElMessage({
        type: 'success',
        message: '操作成功！'
      })

      // 关闭对话框
      dialogFormVisible.value = false

      // 重新发送数据请求
      getTrademarkListData();
      // console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  })
}

// 点击弹出对话框
const showTrademarkDialog = () => {
  // 初始化(清空)对话框中的数据
  Object.assign(trademark, initTrademark()) // Object.assign方法，后值替换或覆盖前值
  if (trademark.id) delete trademark.id; // 有id是因为之前修改时添加的，所以需要删除
  dialogFormVisible.value = true;

  // 弹出对话框时清除校验规则
  trademarkForm.value?.clearValidate();
}

// 点击删除品牌信息
const removeTrademarkInfo = (row: TrademarkModel) => {
  ElMessageBox.confirm('确认要删除该条数据吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 点击确定删除时的操作
      // 首先需要发送删除品牌请求
      await reqDeleteTrademarkInfo(row.id as number);
      // 弹窗提示删除成功
      ElMessage({
        type: 'success',
        message: '删除成功'
      });
      // 当前页是否变化
      currentPage.value = trademarkList.value.length > 1 ? currentPage.value : currentPage.value - 1;
      // 重新渲染数据
      getTrademarkListData();
    })
    .catch(() => {
      // 点击取消删除
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 点击编辑品牌信息
const editTrademarkInfo = (row: TrademarkModel) => {
  // 将需要显示出来的品牌数据给trademark进行赋值，因为数据时响应式的，页面会渲染出来
  Object.assign(trademark, row); // 此时的row中是有id属性的，但是原来的trademark数据中没有id属性
  dialogFormVisible.value = true; // 显示对话框

  // 修改时也需要添加清除校验规则
  trademarkForm.value?.clearValidate();
}


</script>


<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 100%;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>